<template>
  <div class="app-container">
    <!-- 查询栏 -->
    <el-form :model="queryParams" inline>
      <el-form-item label="菜单名称">
        <el-input
          v-model="queryParams.menuName"
          placeholder="请输入菜单名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="状态">
        <el-select
          v-model="queryParams.status"
          placeholder="菜单状态"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">
          搜索
        </el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:menu:add']"
          v-if="!showBtn"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Sort" @click="toggleExpandAll">
          展开/折叠
        </el-button>
      </el-col>
      <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <!-- 表格 -->
    <el-table
      v-if="refreshTable"
       ref="menuTableRef"
      :data="menuList"
      row-key="menuId"
      :default-expand-all="isExpandAll"
      :tree-props="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        v-if="showBtn"
      />

      <el-table-column
        prop="menuName"
        label="菜单名称"
        :show-overflow-tooltip="true"
        width="160"
      />
      <el-table-column label="图标" width="80" align="center">
        <template #default="scope">
          <svg-icon :name="scope.row.icon" color="#409EFF" />
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" width="60" />
      <el-table-column
        prop="perms"
        label="权限标识"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="component"
        label="组件路径"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column label="状态" width="80">
        <template #default="scope">
          {{ scope.row.status === '0' ? '启用' : '停用' }}
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间" width="160">
        <template #default="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="210"
        class-name="small-padding fixed-width"
        v-if="!showBtn"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:menu:edit']"
          >
            修改
          </el-button>
          <el-button
            link
            type="primary"
            icon="Plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:menu:add']"
          >
            新增
          </el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:menu:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 作为子组件的确认和取消 -->
    <div
      v-if="showBtn"
      class="dialog-footer"
      style="text-align: right; margin-top: 16px"
    >
      <el-button @click="$emit('confirm', menuIds)" type="primary">
        确定
      </el-button>
      <el-button @click="$emit('cancel')">取消</el-button>
    </div>

    <!-- 新增/修改弹窗 -->
    <el-dialog v-model="open" :title="title" width="680px">
      <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <el-tree-select
                v-model="form.parentId"
                :data="menuOptions"
                :props="{
                  value: 'menuId',
                  label: 'menuName',
                  children: 'children',
                }"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型">
              <el-radio-group v-model="form.menuType">
                <el-radio value="M">目录</el-radio>
                <el-radio value="C">菜单</el-radio>
                <el-radio value="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.menuType != 'F'">
            <el-form-item label="菜单图标" prop="icon">
              <el-popover placement="bottom-start" :width="540" trigger="click">
                <template #reference>
                  <el-input
                    v-model="form.icon"
                    placeholder="点击选择图标"
                    @blur="showSelectIcon"
                    readonly
                  >
                    <template #prefix>
                      <svg-icon
                        v-if="form.icon"
                        :icon-class="form.icon"
                        class="el-input__icon"
                        style="height: 32px; width: 16px"
                      />
                      <el-icon v-else style="height: 32px; width: 16px">
                        <search />
                      </el-icon>
                    </template>
                  </el-input>
                </template>
                <icon-select
                  ref="iconSelectRef"
                  @selected="selected"
                  :active-icon="form.icon"
                />
              </el-popover>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序">
              <el-input-number
                v-model="form.orderNum"
                ontrols-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.menuType == 'C'">
            <el-form-item prop="routeName">
              <template #label>
                <span>
                  <el-tooltip
                    content="默认不填则和路由地址相同：如地址为：`user`，则名称为`User`（注意：因为router会删除名称相同路由，为避免名字的冲突，特殊情况下请自定义，保证唯一性）"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  路由名称
                </span>
              </template>
              <el-input v-model="form.routeName" placeholder="请输入路由名称" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="权限标识">
              <el-input v-model="form.perms" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="组件路径" v-if="form.menuType === 'C'">
              <el-input v-model="form.component" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue'
import iconSelect from '@/components/IconSelect/index.vue'
import {
  reqMenuTreeByCondition,
  reqMenuAdd,
  reqMenuOne,
  reqMenuDel,
  reqMenuUpdate,
  reqAssignedMenu,
} from '@/api/menu/index'
import { Menu } from '@/api/menu/type'
import { R } from '@/api/common/type'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'

const menuTableRef = ref<null>(null)

const showBtn = ref(false)
const menuIds = ref<number[]>([])

// 放在 <script setup> 末尾
const props = defineProps<{
  roleId: number | null // 当前角色 id
}>()

const emit = defineEmits<{
  confirm: [menuIds: number[]] // 点击确定时把选中的 id 数组回传
  cancel: [] // 点击取消
}>()

// 组件挂载时加载数据
onMounted(() => {
  console.log('dialog roleId==>', props.roleId)
  handleQuery()
  if (props.roleId !== undefined) {
    showBtn.value = true
  }
})

/** 多选框选中数据 */
function handleSelectionChange(selection: any[]) {
  // menuIds.value = selection.map((item: any) => item.menuId)
 // 获取所有选中节点的ID
  const selectedIds = selection.map(item => item.menuId);

  menuIds.value = selectedIds

  console.log("select ========== >",selectedIds)

// 获取所有节点（扁平化树结构）
  // const allNodes = flattenTree(menuList.value);


  // console.log("all node==", allNodes)
  // allNodes.forEach((row) => {
  //         if (row.menuId === 100) {
  //           menuTableRef.value?.toggleRowSelection(row, true)
  //         }
  //       })
  
//   // 计算需要收集的菜单ID（包括全选和半选节点）
//   menuIds.value = calculateSelectedMenuIds(allNodes, selectedIds);
  
//   // 更新表格的选中状态（包括半选状态）
//   updateTableSelections(allNodes, selectedIds);


}



/**
 * 扁平化树结构
 */
 function flattenTree(tree: Menu[]): Menu[] {
  const result: Menu[] = [];
  
  function dfs(list: Menu[]) {
    list.forEach((node) => {
      result.push(node);
      if (node.children && node.children.length > 0) {
        dfs(node.children);
      }
    });
  }
  
  dfs(tree);
  return result;
}

// ======== 1. 本地字典数据 ========
const sys_normal_disable = [
  { label: '启用', value: '0' },
  { label: '停用', value: '1' },
]
const sys_show_hide = [
  { label: '显示', value: '0' },
  { label: '隐藏', value: '1' },
]

// ======== 3. 工具函数 ========
function parseTime(timestamp: string | number | Date) {
  return new Date(timestamp).toLocaleString()
}

// ======== 4. 响应式数据 ========
const menuList = ref<Menu[]>([])

const menuOptions = ref([
  { menuId: 0, menuName: '创建根目录', children: menuList },
])

const loading = ref(false)
const showSearch = ref(true)
const isExpandAll = ref(false)
const refreshTable = ref(true)
const open = ref(false)
const title = ref('')

const queryParams = reactive({
  menuName: '',
  // status: '',
})

const form = reactive({
  menuId: undefined,
  parentId: 1,
  menuName: '',
  icon: 'Edit',
  menuType: 'M',
  orderNum: 0,
  isFrame: '1',
  isCache: '0',
  visible: '0',
  status: '0',
  perms: '',
  component: '',
  url: '',
  target: '',
  remark: '',
})

const rules = {
  menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
}

// ======== 5. 业务逻辑 ========
const handleQuery = async () => {
  const result: R<Menu[]> = await reqMenuTreeByCondition(queryParams)

  console.log('result====>', result)

  menuList.value = result.data
}

function resetQuery() {
  queryParams.menuName = ''
}

function reset() {
  Object.assign(form, {
    menuId: undefined,
    parentId: 1,
    menuName: '',
    icon: '',
    menuType: 'M',
    orderNum: 0,
    isFrame: '1',
    isCache: '0',
    visible: '0',
    status: '0',
    perms: '',
    component: '',
  })
}

/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset()
}

/** 选择图标 */
function selected(name: string) {
  console.log('选择的icon===>', name)
  form.icon = name
}

function handleAdd(row: { menuId: number }) {
  reset()
  // 安全处理 row 参数
  if (row && row.menuId) {
    form.parentId = row.menuId
  } else {
    form.parentId = 0 // 默认为根节点
  }
  open.value = true
  title.value = '添加菜单'
}

function handleUpdate(row: any) {
  if (!row) return // 兜底
  reset()
  Object.assign(form, row)
  open.value = true
  title.value = '修改菜单'
}

const submitForm = async () => {
  // 真实场景做校验+保存
  if (form.menuId) {
    const updateRes: R<boolean> = await reqMenuUpdate(form)

    if (!updateRes || !updateRes.data) {
      ElMessage.error('更新权限失败 ！')
      return
    }

    const result: R<Menu> = await reqMenuOne(form.menuId)

    if (result && result.code === 200) {

      // 修改：直接把原数组中对应节点替换掉
      updateTreeNode(menuList.value, result.data)

      ElMessage.success('更新权限成功 ！')
      open.value = false
    } else {
      ElMessage.error('更新权限失败 ！')
    }
  } else {
    const result: R<boolean> = await reqMenuAdd(form)

    if (result && result.code === 200) {
      ElMessage.success('新增权限成功 ！')
      open.value = false
      handleQuery() // 刷新
    } else {
      ElMessage.error('新增权限失败 ！')
    }
  }
}

const handleDelete = async(row: { menuId: any }) => {
console.log("deleted ========>" ,row)
  const result: R<boolean> = await reqMenuDel(row.menuId)
    if (result && result.code === 200) {
      ElMessage.success('删除权限成功 ！')
      open.value = false
      handleQuery() // 刷新
    } else {
      ElMessage.error('删除权限失败 ！')
    }
  handleQuery()
}

function updateTreeNode(tree: Menu[], newNode: Menu): boolean {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i].menuId === newNode.menuId) {
      tree[i] = { ...tree[i], ...newNode }
      return true
    }
    if (tree[i].children && tree[i].children.length > 0) {
      const found = updateTreeNode(tree[i].children, newNode)
      if (found) return true
    }
  }
  return false
}

function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => (refreshTable.value = true))
}

function cancel() {
  open.value = false
}
</script>
